var wxCharts = require('../../../../utils/wxcharts');
var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
var pieChart = null;
var filePieChart = null;
var lineChart = null;
const app = getApp()
Page({
  data: {
    // 统计维度
    dimension:'month',
    // 选择的开始时间
    selectStartDate:null,
    // 选择的开始时间
    selectEndDate:null,
    // 公司id
    companyId:0,
    // 盖章总数
    total:100,
    // 排行榜数据1
    rankingListData:[],
    windowWidth:300,
    windowHeight:600,
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '用印统计明细', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     navbarHeight: app.globalData.height * 2 + 20
  },  
  onLoad: function () {
    var _this = this;
    requestClient = new ZYRequestClient();
    _this.initData();
  },
  onShow: function () {
    var _this = this;
    _this.loadStatisticsData();
  },
  initData(){
    var _this = this;
    pieChart = null;
    filePieChart = null;
    lineChart = null;
    var statisticsParamsData = wx.getStorageSync('statisticsParamsData')
    _this.setData({
      dimension:statisticsParamsData.dimension,
      year:statisticsParamsData.year,
      month:statisticsParamsData.month,
      yearMonth:statisticsParamsData.yearMonth,
      selectStartDate:statisticsParamsData.selectStartDate,
      selectEndDate:statisticsParamsData.selectEndDate,
      rankingData:statisticsParamsData.rankingData,
      rankingType:statisticsParamsData.rankingData.type,
    });
    // 获取手机宽度和高度
    wx.getSystemInfo({
      success: (result) => {
        _this.setData({
          windowWidth:result.windowWidth,
          windowHeight:result.windowHeight,
        });
      },
    })
    var defaultCompany = wx.getStorageSync('defaultCompany');
    _this.setData({
      companyId:defaultCompany.id,
    });
  },
  // 加载统计数据
  loadStatisticsData(){
    var _this = this;
    var paramsData = {
      companyId:_this.data.companyId,
      startTime:_this.data.selectStartDate,
      endTime:_this.data.selectEndDate,
      dimension:_this.data.dimension,
      type:_this.data.rankingData.type,
      value:_this.data.rankingData.id,
    };
    if(paramsData.type=='contract'){
      paramsData.value = _this.data.rankingData.name;
    }
    _this.setData({
      statisticsParams:paramsData,
    });
    wx.showLoading({
      title: '计算中...',
    })
    requestClient.getStatisticsData(paramsData,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      _this.setData({
        total:res.data.data.total,
      });
      var rankingListData = res.data.data.rankingList;
      if(rankingListData == null){
        rankingListData = [];
      }
      _this.setData({
        rankingListData:rankingListData,
      });
      var approvalCount = res.data.data.approvalCount;
      if(approvalCount == null){
        approvalCount = 0;
      }
      var noneApprovalCount = res.data.data.noneApprovalCount;
      if(noneApprovalCount == null){
        noneApprovalCount = 0;
      }
      var lineChartCategories = res.data.data.lineChartCategories;
      if(lineChartCategories == null){
        lineChartCategories = [1];
      }
      var lineChartSeries = res.data.data.lineChartSeries;
      if(lineChartSeries == null){
        lineChartSeries = [0];
      }
      if(pieChart){
        pieChart.updateData({
          series: [{
              name: '审批用印',
              data: approvalCount,
          }, {
              name: '无审批用印',
              data: noneApprovalCount,
          }],
        });
      } else {
        // 饼图
        pieChart = new wxCharts({
          animation: true,
          canvasId: 'pieCanvas',
          type: 'pie',
          series: [{
              name: '审批用印',
              data: approvalCount,
          }, {
              name: '无审批用印',
              data: noneApprovalCount,
          }],
          width: _this.data.windowWidth,
          height: 200,
          dataLabel: true,
        });
      }
      if(lineChart){
        lineChart.updateData({
          categories: lineChartCategories, 
          series: [{ 
            name: '盖章次数', 
            data: lineChartSeries}
          ], 
        });
      } else {
        // 折线图
        lineChart = new wxCharts({ 
          animation: true,
          canvasId: 'lineCanvas', 
          type: 'line', 
          categories: lineChartCategories, 
          series: [{ 
            name: '盖章次数', 
            data: lineChartSeries}
          ], 
          yAxis: { 
            min: 0 
          },
          width: _this.data.windowWidth, 
          height: 200 
        });
      }
      var contractList = [];
      for(var i = 0; i<rankingListData.length;i++){
        if(rankingListData[i].type =='contract'){
          var contract = {
            name:rankingListData[i].name,
            data:rankingListData[i].stampCount,
          };
          contractList.push(contract);
        }
      }
      if(contractList.length == 0){
        var contract = {
          name:"暂无文件",
          data:0,
        };
        contractList.push(contract);
      }
      if(filePieChart){
        filePieChart.updateData({
          series: contractList,
        });
      } else {
        filePieChart = new wxCharts({
          animation: true,
          canvasId: 'filePieCanvas',
          type: 'pie',
          series: contractList,
          width: _this.data.windowWidth,
          height: 200,
          dataLabel: true,
        });
      }
    });
  },
  // 选择年月
  bindMonthChange(e){
    var _this = this;
    var yearMonth = e.detail.value;
    var year = yearMonth.split('-')[0];
    year = parseInt(year);
    var month = yearMonth.split('-')[1];
    var newYearMonth = yearMonth.replace(/-/,'年');
    _this.setData({
      year:year,
      month:month,
      yearMonth:newYearMonth,
      selectStartDate:yearMonth + '-01 00:00:00',
    });
    // 选择时间增加一个月
    var endDate = new Date(yearMonth + '-01');
    endDate.setMonth(endDate.getMonth() + 1);
    var endYear = endDate.getFullYear();
    var endMonth = endDate.getMonth() + 1;
    if(endMonth >=1 && endMonth <=9){
      endMonth = '0' + endMonth;
    }
    _this.setData({
      selectEndDate:endYear + '-' + endMonth + '-01 00:00:00',
    });
    // 加载统计数据
    _this.loadStatisticsData();
  },
  // 选择年份
  bindYearChange(e){
    var _this = this;
    var year = e.detail.value;
    year = parseInt(year);
    _this.setData({
      year:year,
      yearMonth:year + '年' + _this.data.month,
      selectStartDate:year + '-01-01 00:00:00',
      selectEndDate:(year+1) + '-01-01 00:00:00',
    });
    // 加载统计数据
    _this.loadStatisticsData();
  },
  // 切换统计维度
  bindSwitchDimension(e){
    var _this = this;
    var dimension = e.currentTarget.dataset.dimension;
    _this.setData({
      dimension:dimension
    });
    if(dimension == "month"){
      _this.setData({
        selectStartDate:_this.data.year + '-' + _this.data.month  + '-01 00:00:00',
      });
      // 选择时间增加一个月
      var endDate = new Date(_this.data.year + '-' + _this.data.month + '-01');
      endDate.setMonth(endDate.getMonth() + 1);
      var endYear = endDate.getFullYear();
      var endMonth = endDate.getMonth() + 1;
      if(endMonth >=1 && endMonth <=9){
        endMonth = '0' + endMonth;
      }
      _this.setData({
        selectEndDate:endYear + '-' + endMonth + '-01 00:00:00',
      });
    } else {
      _this.setData({
        selectStartDate:_this.data.year + '-01-01 00:00:00',
        selectEndDate:(_this.data.year+1) + '-01-01 00:00:00',
      });
    }
    // 加载统计数据
    _this.loadStatisticsData();
  },
  // 切换排行榜
  bindSwitchRanking(e){
    var _this = this;
    var type = e.currentTarget.dataset.type;
    _this.setData({
      rankingType:type
    });
  },
  // 查看记录
  bindScanStampRecord(e){
    var _this = this;
    var statisticsStampParams = {
      startTime:_this.data.selectStartDate,
      endTime:_this.data.selectEndDate,
      hasAdmin:true,
      companyId:_this.data.companyId,
      pageNo:0,
    };
    if(_this.data.rankingData.type == 'contract'){
      statisticsStampParams.fileType=_this.data.rankingData.name
    } else if(_this.data.rankingData.type == 'user'){
      statisticsStampParams.stampUserId=_this.data.rankingData.id
    } else {
      statisticsStampParams.sealId=_this.data.rankingData.id
    }
    // 查询参数存储到离线缓存
    wx.setStorageSync('statisticsStampParams', statisticsStampParams);
    // 跳转记录页面
    wx.navigateTo({
      url: '../statisticsrecord/index',
    })
  },
  // 导出报表
  bindReport(e){
    var _this = this;
    wx.showLoading({
      title: '正在导出...',
    })
    requestClient.getStatisticsReport(_this.data.statisticsParams,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      const fs = wx.getFileSystemManager();
      fs.writeFile({
        filePath: wx.env.USER_DATA_PATH + "/统计报表.xls", // wx.env.USER_DATA_PATH 指定临时文件存入的路径，后面字符串自定义
        data: res.data,
        encoding: "binary", //二进制流文件必须是 binary
        success (res){
          wx.openDocument({ // 打开文档
            filePath: wx.env.USER_DATA_PATH + "/统计报表.xls",  //拿上面存入的文件路径
            showMenu: true, // 显示右上角菜单
            success: function (res) {
              setTimeout(()=>{wx.hideLoading()},500)
            }
          })
        }
      })
    });
  }
})